package com.zkingsoft.thread;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.dingtalk.open.client.api.model.corp.MessageBody;
import com.dingtalk.open.client.api.model.corp.MessageBody.OABody.Body;
import com.dingtalk.open.client.api.model.corp.MessageBody.OABody.Body.Form;
import com.dingtalk.open.client.api.model.corp.MessageBody.OABody.Head;
import com.dingtalk.open.client.api.model.corp.MessageType;
import com.zkingsoft.dao.TaskDao;
import com.zkingsoft.dingding.Env;
import com.zkingsoft.dingding.Vars;
import com.zkingsoft.dingding.auth.AuthHelper;
import com.zkingsoft.dingding.message.LightAppMessageDelivery;
import com.zkingsoft.dingding.message.MessageHelper;
import com.zkingsoft.model.Task;
import com.zkingsoft.model.Users;
import com.zkingsoft.plugin.util.DateUtils;
import com.zkingsoft.services.TaskService;

/**
 * 发送与任务相关的消息通知线程类
 * @author Administrator
 *
 */
public class SendOaMsgsThread implements Runnable {
	
	TaskService taskService = null;
	TaskDao taskDao = null;
	List<Long> list = null;
	String bgColor = null;
	String title = null;
	//发送任务OA消息提醒，OA消息体,map对象中请放入两个key：key,value
	List<Map<String, String>> msgList = null;
	boolean isCreateUser ; //消息发送个谁，true:创建人，false:指派人
	boolean flag = false;
	
	public SendOaMsgsThread(TaskService taskService, List<Long> list, 
			String bgColor, String title, boolean isCreateUser,List<Map<String, String>> msgList) {
		this.taskService = taskService;
		this.list = list;
		this.bgColor = bgColor;
		this.title = title;
		this.isCreateUser = isCreateUser;
		this.msgList = msgList;
	}
	
	public SendOaMsgsThread(TaskDao taskDao, List<Long> list, 
			String bgColor, String title, boolean isCreateUser, List<Map<String, String>> msgList) {
		this.taskDao = taskDao;
		this.list = list;
		this.bgColor = bgColor;
		this.title = title;
		this.isCreateUser = isCreateUser;
		this.msgList = msgList;
	}



	@Override
	public void run() {
			if(taskService!=null){
				flag = sendOaMsgs();
			}
			if(taskDao!=null){
				flag = sendOaMsgsInService();
			}			
	}	
	
	/**
	 * @Description:批量发送oa通知,供controller层使用
	 * @author: dingchuan
	 * @param taskIds 新增的任务id集合
	 * 返回类型 void
	 * @date 2016年12月5日
	 */
	public boolean sendOaMsgs(){
		try {
			StringBuffer sb = new StringBuffer();
			if(list.size()>0){
				sb.append(list.get(0));
			}
			for (int i = 1; i < list.size(); i++) {
				sb.append(",");
				sb.append(list.get(i));
			}
			List<Task> tasks = taskService.findTaskAndDdUserId(sb.toString());
			if(tasks!=null && tasks.size() > 0){					
				//循环发送OA消息
				String accessToken = AuthHelper.getAccessToken();//获取accessToken
				String toUsers = "";
				String toParties = Vars.TO_PARTY;
				String agentId = Vars.AGENT_ID;
				for (Task task : tasks) {					
					//创建oa消息
					MessageBody.OABody oaBody = createOaMsg(task);
					// 发送微应用消息
					//给创建人或者指派人发送
					if(isCreateUser){
						toUsers = task.getCreateValidateCode();
					}else{
						toUsers = task.getUserValidateCode();
					}
					LightAppMessageDelivery lightAppMessageDelivery = new LightAppMessageDelivery(toUsers, toParties, agentId);
					lightAppMessageDelivery.withMessage(MessageType.OA, oaBody);					
					MessageHelper.send(accessToken, lightAppMessageDelivery);
					//给关注人发送
					String concernIds = task.getConcernId();
					if(!"".equals(concernIds)&& concernIds != null){
						List<Users> usersList = taskService.findByIdStr(concernIds);
						if(usersList!=null && usersList.size()>0){
							for (Users user : usersList) {
								toUsers = user.getValidateCode();
								LightAppMessageDelivery lightAppMessageDelivery2 = new LightAppMessageDelivery(toUsers, toParties, agentId);
								lightAppMessageDelivery2.withMessage(MessageType.OA, oaBody);					
								MessageHelper.send(accessToken, lightAppMessageDelivery2);
							}
						}
					}
					
				}
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;	
	}
	
	
	/**
	 * @Description:批量发送oa通知,供Service层使用
	 * @author: dingchuan
	 * @param taskIds 新增的任务id集合
	 * 返回类型 void
	 * @date 2016年12月5日
	 */
	public boolean sendOaMsgsInService(){
		try {
			StringBuffer sb = new StringBuffer();
			if(list.size()>0){
				sb.append(list.get(0));
			}
			for (int i = 1; i < list.size(); i++) {
				sb.append(",");
				sb.append(list.get(i));
			}
//			List<Task> tasks = taskService.findTaskAndDdUserId(sb.toString());
			List<Task> tasks = taskDao.selectTaskAndDdUserId(sb.toString());
			if(tasks!=null && tasks.size() > 0){	
				//循环发送OA消息
				String accessToken = AuthHelper.getAccessToken();//获取accessToken
				String toUsers =  "";
				String toParties = Vars.TO_PARTY;
				String agentId = Vars.AGENT_ID;
				//循环发送OA消息
				for (Task task : tasks) {
					//创建oa消息
					MessageBody.OABody oaBody = createOaMsg(task);
					if(isCreateUser){
						toUsers = task.getCreateValidateCode();
					}else{
						toUsers = task.getUserValidateCode();
					}					
					LightAppMessageDelivery lightAppMessageDelivery = new LightAppMessageDelivery(toUsers, toParties, agentId);
					lightAppMessageDelivery.withMessage(MessageType.OA, oaBody);
					MessageHelper.send(accessToken, lightAppMessageDelivery);
					//Service中只有新增任务的时候才会发送消息通知，此时还没有关注者
				}
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;	
	}
	
	/**
	 * @Description:创建OA消息
	 * @author:dingchuan
	 * @param task
	 * @return
	 * 返回类型 MessageBody.OABody
	 * @date 2016年12月6日
	 */
	public MessageBody.OABody createOaMsg(Task task){
		SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.DATE_FORMAT_DD);
		MessageBody.OABody oaBody = new MessageBody.OABody();
        oaBody.setMessage_url(Env.LOOK_MESSAGE + task.getId());
        oaBody.setPc_message_url(Env.LOOK_MESSAGE + task.getId());
        //头部
        Head head = new Head();
        head.setText("");
        head.setBgcolor(bgColor);
        oaBody.setHead(head);
        //内容
        Body body = new Body();
        body.setTitle(task.getName());
        List<Form> formList = new ArrayList<Form>();
        if(msgList == null){
        	Form form4 = new Form();//新建还是开始，还是取消或则完成
            form4.setKey("任务状态");
            form4.setValue(title);
            formList.add(form4);
            Form form5 = new Form();
            Form form2 = new Form();
            form2.setKey("任务类型");
            form2.setValue(task.getTaskType());
            formList.add(form2);
            form5.setKey("指派人");
            form5.setValue(task.getAssignName());
            formList.add(form5);
            Form form = new Form();
            form.setKey("创建人");
            form.setValue(task.getCreateName());
            formList.add(form);
            Form form1 = new Form();
            form1.setKey("任务等级");
            form1.setValue(task.getLevel()+"级任务");
            formList.add(form1);
            Form form3 = new Form();
            form3.setKey("预计结束时间");
            form3.setValue(sdf.format(task.getEndTime()));
            formList.add(form3);
        }else{
        	for (Map<String, String> map : msgList) {
				Form form = new Form();
				form.setKey(map.get("key"));
				form.setValue(map.get("value"));
				formList.add(form);
			}
        }
        body.setForm(formList);
        oaBody.setBody(body);
		return oaBody;
	}
	      
	
	
}
